package com.glodon.paas.sdk.account;

import javax.ws.rs.core.MediaType;

import com.glodon.paas.account.api.bean.User;
import com.glodon.paas.sdk.PaasClient;
import com.glodon.paas.sdk.SdkException;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;

public class Account {
	
	private final static String PATH_USER_INFO = "/user";
	
	private PaasClient client;
	
	/**
	 * @param client PAAS客户端
	 */
	public Account(PaasClient client) {
		this.client = client;
	}
	
	/**
	 * 根据path生成对应的uri地址
	 * @param path 相对路径
	 * @return URI
	 */
	public String endpoint(String path) {
		return client.getEndpointConfig().accountEndpoint(path).toString();
	}
	
	/**
	 * 获取当前登录者信息
	 * @return  json格式的字符串
	 * @throws SdkException
	 */
	public String getUserInfoAsJson() throws SdkException {
		String api = endpoint(PATH_USER_INFO);
		WebResource resource = client.signAndCreateResource(api, "GET");
		ClientResponse c = resource.type(MediaType.APPLICATION_JSON_TYPE).get(ClientResponse.class);
		if(c.getStatus() != 200){
			throw new SdkException(c.getEntity(String.class));
		}
		return c.getEntity(String.class);
	}
	
	/**
	 * 获取当前登录者信息
	 * @return 用户信息
	 * @throws SdkException
	 */
	public User getUserInfo() throws SdkException{
		String api = endpoint(PATH_USER_INFO);
		WebResource resource = client.signAndCreateResource(api, "GET");
		ClientResponse c = resource.type(MediaType.APPLICATION_JSON_TYPE).get(ClientResponse.class);
		if(c.getStatus() != 200){
			throw new SdkException(c.getEntity(String.class));
		}
		return c.getEntity(User.class);
	}
}
